"use client"
import { LockOutlined, UserOutlined } from "@ant-design/icons"
import { LoginForm, ProFormText } from "@ant-design/pro-components"
import React, { useRef } from "react"
import Image from "next/image"
import Link from "next/link"
import { userLogin } from "@/api/user"
import { message } from "antd"
import { useAppDispatch } from "@/stores"
import { setLoginUserAction } from "@/stores/features/login-user"
import { useRouter } from "next/navigation"
import type { ProFormInstance } from "@ant-design/pro-components"

/**
 * 用户登录页面
 */
const UserLoginPage: React.FC = () => {
  const formRef = useRef<ProFormInstance>()
  const dispatch = useAppDispatch()
  const router = useRouter()

  const doSubmit = async (values: UserLoginRequest) => {
    try {
      const res = await userLogin(values)
      if (res.data) {
        dispatch(setLoginUserAction(res.data))
        message.success("登录成功")
        router.replace("/")
        formRef.current?.resetFields()
      }
    } catch (error) {
      error instanceof Error && message.error("登录失败，" + error)
    }
  }

  return (
    <div id="user-login-page">
      <LoginForm
        formRef={formRef}
        logo={<Image src="/assets/logo.png" alt="面试鸭" width={44} height={44} />}
        title="面试鸭 - 用户登录"
        subTitle="面试刷题网站"
        onFinish={doSubmit}
      >
        <ProFormText
          name="userAccount"
          fieldProps={{
            size: "large",
            prefix: <UserOutlined />
          }}
          placeholder={"请输入用户账号"}
          rules={[
            {
              required: true,
              message: "请输入用户账号！"
            }
          ]}
        />
        <ProFormText.Password
          name="userPassword"
          fieldProps={{
            size: "large",
            prefix: <LockOutlined />
          }}
          placeholder={"请输入密码"}
          rules={[
            {
              required: true,
              message: "请输入密码！"
            }
          ]}
        />
        <div
          style={{
            marginBlockEnd: 24,
            textAlign: "right"
          }}
        >
          还没有账号？
          <Link href="/user/register">去注册</Link>
        </div>
      </LoginForm>
    </div>
  )
}

export default UserLoginPage
